from flask import render_template, current_app, request, session, jsonify, g

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


@index_blu.route("/news_list")
def news_list():
    """
    获取首页新闻数据
    :return:
    """

    # 1.获取参数
    # 新闻的分类id,分页页数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 3. 查询数据并分页
    filters = [News.status == 0]
    if cid != 1:  # 查询的不是最新的数据
        #　需要添加条件
        filters.append(News.category_id == cid)

    # 3.查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        # 获取查询出来的数据
        items = paginate.items
        # 获取到总页数
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_li = []
    for news in items:
        news_li.append(news.to_basic_dict())
    # 返回json数据
    return jsonify(errno=RET.OK, errmsg="OK", totalPage=total_page, currentPage=current_page, newsList=news_li, cid=cid)



@index_blu.route("/")
@user_login_data
def index():
    user = g.user
    # # 取出新闻排行列表
    # news_li = News.query().order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    try:
        category_li = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_dict_li = []
    for category in category_li:
        category_dict_li.append(category.to_dict())
    data = {
        "user_dict": user.to_dict() if user else None,  # 查询出用户的数据
        "news_dict_li": news_dict_li,
        "categories": category_dict_li
    }
    return render_template("news/index.html", data=data)



# 在打开网页的时候，浏览器会默认去请求根路径+favicon.ico作网站标签的小图标
@index_blu.route("/favicon.ico")
def favicon():
    # app的send_static_file的方法可以向浏览器发送静态文件
    return current_app.send_static_file("news/favicon.ico")